<template>
  <div class="page-view">
    <div class="tip-usage d-flex px-8 py-5 fs-xs">
      <SvgIcon
        class-name="mr-4 flex-shrink-0"
        icon-class="warn"
      />使用提示：场景页模版类型中，新增页面可通过组件进行跳转展示
    </div>
    <div class="d-flex jc-between pt-24 px-24 pb-32">
      <el-button type="primary" class="btn-addNewPage" @click="addNewPage">
        <i class="icon icon-new-page mr-4"></i>新增页面
      </el-button>
      <div class="btn-background d-flex jc-center al-center t-light pointer" @click="dialogType = 'pageBackground'">
        <i class="icon icon-fill-background mr-4"></i>页面背景
      </div>
    </div>
    <vuedraggable
      :list="pageConfigList"
      class="page-wrapper"
      :scroll-sensitivity="100"
      animation="300"
      :fallback-tolerance="10"
      :force-fallback="true"
      fallback-class="force-fallback"
      @start="onPageStart"
      @sort="onPageSort"
    >
      <div
        v-for="(page, i) in pageConfigList"
        :key="i"
        class="d-flex jc-center pb-32 pointer"
        :class="{ active: activePageIndex === i }"
        @click="activePage(i)"
      >
        <div class="d-flex flex-column al-center mr-16">
          <div class="page-index fw-bold t-center">{{ i + 1 }}</div>
          <el-tooltip effect="dark" placement="bottom">
            <div slot="content" class="fs-xs">已设置翻页</div>
            <i v-show="page.pageTurn.turnable" class="icon icon-turn-animation mt-8"></i
          ></el-tooltip>
        </div>
        <div class="page-item d-flex p-16" :class="{ home: i === 0 }">
          <div class="pic-thumbnails"><i class="icon icon-create absCenter"></i></div>
          <div class="d-flex flex-column jc-between al-start flex-1 ml-24">
            <div v-if="editNameId === page.id">
              <el-input
                v-model.trim="page.name"
                class="aside-page-name-input"
                maxlength="10"
                @blur.stop="editedPageName(editNameId)"
              >
                <template #suffix><i class="icon icon-editing"></i></template>
              </el-input>
            </div>
            <div v-else class="page-title d-flex jc-between align-center fulled-w fw-bold">
              {{ page.name }} <i class="icon icon-edit" @click.stop="editPageName(page.id)"></i>
            </div>
            <div class="t-light">
              <div
                class="d-flex al-center mb-16"
                :style="{ color: i === 0 ? '#DBDBDB' : 'inherit' }"
                @click.stop="setHomePage(i)"
              >
                <SvgIcon icon-class="home" class-name="icon mr-4"></SvgIcon>设为首页
              </div>
              <div class="d-flex al-center mb-16" @click.stop="copyPage(i)">
                <i class="icon icon-copy mr-4"></i>复制页面
              </div>
              <div v-if="pageConfigList.length > 1" class="d-flex al-center" @click.stop="openDeleteDialog(i)">
                <i class="icon icon-delete mr-4"></i>删除页面
              </div>
            </div>
          </div>
        </div>
      </div>
    </vuedraggable>
    <!-- 设置页面背景 -->
    <el-dialog
      class="pageBackground-dialog"
      :visible="dialogType === 'pageBackground'"
      width="500px"
      title="设置全局背景"
      @close="dialogType = ''"
    >
      <div class="tip d-flex al-center mb-12 fs-xs px-8 t-grey">
        <SvgIcon class-name="mr-4" icon-class="warn" />设置内容将应用至所有页面，请谨慎选择
      </div>
      <el-form label-width="88px">
        <BackgroundSetting v-model="pageBackground" />
      </el-form>
      <template #footer>
        <el-button class="btn-cancel" @click="dialogType = ''">取消</el-button>
        <el-button class="btn-confirm ml-24" type="primary" @click="setPageBackground">确定</el-button>
      </template>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog :visible="dialogType === 'pageDelete'" width="448px" @close="dialogType = ''">
      <div slot="title" class="d-flex al-center" style="font-size: 20px">
        <i class="el-icon-warning mr-5" style="font-size: 18px; color: #ff9316"></i>提示
      </div>
      <div style="min-height: 52px">
        <p class="mb-8">您确定要删除该页面吗?</p>
        <p class="t-light">删除后将不可恢复</p>
      </div>
      <template #footer>
        <el-button class="btn-cancel" @click="dialogType = ''">取消</el-button>
        <el-button class="btn-confirm ml-24" type="primary" @click="delPage">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters, mapMutations } from 'vuex';
  import { deepClone, generateID, decodePageStyle } from '@/utils';
  import vuedraggable from 'vuedraggable';
  import BackgroundSetting from '@/views/productEdit/components/settingComponent/BackgroundSetting';

  export default {
    components: { vuedraggable, BackgroundSetting },
    inject: [
      'getActivePageIndex',
      'setActivePageIndex',
      'getPageConfigList',
      'getWidgetConfigList',
      'generatePageConfig'
    ],
    data() {
      return {
        editPageIndex: 0,
        editNameId: '',
        pageBackground: decodePageStyle({ fillType: 0, backgroundColor: '' }),
        dialogType: ''
      };
    },
    computed: {
      ...mapGetters('component', ['scaleRatio']),
      activePageIndex() {
        return this.getActivePageIndex();
      },
      pageConfigList() {
        return this.getPageConfigList();
      },
      widgetConfigList() {
        return this.getWidgetConfigList();
      }
    },
    methods: {
      ...mapMutations('component', [
        'RECORD_SNAPSHOT',
        'SET_COMPONENTDATA',
        'SET_SNAPSHOTDATA',
        'DEPRESS_COMPONENT',
        'SET_PREVIEWER'
      ]),
  created(){

  },

      // 激活页面
      activePage(i) {
        console.log("传过来的pageConfigList",this.pageConfigList);
        this.SET_SNAPSHOTDATA(this.pageConfigList[i].snapshotData);
        this.DEPRESS_COMPONENT();
        this.SET_COMPONENTDATA(this.widgetConfigList[i]);
        this.SET_PREVIEWER(this.pageConfigList[i].size);
        if (this.activePageIndex !== i) document.querySelector('#preview-scroller').scrollTop = 0;
        this.setActivePageIndex(i);
      },

      // 复制页面
      copyPage(i) {
        const pageConfigClone = deepClone(this.pageConfigList[i]);
        pageConfigClone.id = generateID();
        pageConfigClone.name = this._generateCopyName(pageConfigClone.name);
        pageConfigClone.snapshotData = { index: -1, data: [] };
        this.pageConfigList.splice(i + 1, 0, pageConfigClone);
        const widgetConfigClone = deepClone(this.widgetConfigList[i]);
        this.widgetConfigList.splice(i + 1, 0, widgetConfigClone);
        this.activePage(i + 1);
        this.RECORD_SNAPSHOT();
        this.$EventBus.$emit('hook:ChangeSettingPanel', 'pageSetting');
        this.editPageName(pageConfigClone.id);
      },

      // 新增页面
      addNewPage() {
        const pageConfig = this.generatePageConfig();
        pageConfig.name = this._generatePageName();
        this.pageConfigList.push(pageConfig);
        this.widgetConfigList.push([]);
        this.activePage(this.pageConfigList.length - 1);
        this.RECORD_SNAPSHOT();
        this.$EventBus.$emit('hook:ChangeSettingPanel', 'pageSetting');
        this.editPageName(pageConfig.id);
      },

      // 删除页面
      openDeleteDialog(i) {
        this.editPageIndex = i;
        this.dialogType = 'pageDelete';
      },
      delPage() {
        const i = this.editPageIndex;
        // 先解除引用该页面的 组件config.jump
        const pageId = this.pageConfigList[i].id;
        this.widgetConfigList.forEach((widgets) => {
          widgets.forEach((widget) => {
            if (widget.config.url === pageId) widget.config.url = '';
          });
        });
        this.pageConfigList.splice(i, 1);
        this.widgetConfigList.splice(i, 1);
        this.activePageIndex >= i && this.activePageIndex !== 0
          ? this.activePage(this.activePageIndex - 1)
          : this.activePage(this.activePageIndex);
        this.dialogType = '';
      },

      // 设为首页
      setHomePage(i) {
        if (i === 0) return;
        this.pageConfigList.unshift(this.pageConfigList.splice(i, 1)[0]);
        this.widgetConfigList.unshift(this.widgetConfigList.splice(i, 1)[0]);
        this.activePage(0);
      },

      // 设置页面背景(统一)
      setPageBackground() {
        this.pageConfigList.forEach((pageConfig) => {
          pageConfig.pageStyle = deepClone(this.pageBackground);
        });
        this.dialogType = '';
      },

      // 页面开始拖动时
      onPageStart(e) {
        this.activePage(e.oldDraggableIndex);
      },

      // 页面排序时——交换位置
      onPageSort(e) {
        const newIndex = e.newDraggableIndex;
        const oldIndex = e.oldDraggableIndex;
        const widgetConfig = this.widgetConfigList[oldIndex];
        this.widgetConfigList[oldIndex] = this.widgetConfigList[newIndex];
        this.widgetConfigList[newIndex] = widgetConfig;
        this.activePage(newIndex);
      },

      // 编辑页面名称
      editPageName(pageId) {
        this.editNameId = pageId;
        this.$nextTick(() => {
          document.querySelector('.aside-page-name-input input').focus();
        });
      },

      // 编辑页面名称完成时
      editedPageName(pageId) {
        const editPage = this.pageConfigList.find((page) => page.id === pageId);
        const editPageId = editPage.id;
        const editPageName = editPage.name;
        const hasSameName = this.pageConfigList.some((page) => page.name === editPageName && page.id !== editPageId);
        if (hasSameName) {
          this.$message.error('页面名称不可重复！');
          document.querySelector('.aside-page-name-input input').focus();
        } else {
          this.editNameId = '';
        }
      },

      // 生成不重复的页面名称：未命名+序号
      _generatePageName() {
        let index = 0;
        let name = '';
        let hasSameName = false;
        do {
          index += 1;
          name = '未命名' + index;
          hasSameName = this.pageConfigList.some((page) => page.name === name);
        } while (hasSameName);
        return name;
      },

      // 生成不重复的副本名称：页面名+'副本'+序号
      _generateCopyName(pageName) {
        let index = 0;
        let name = '';
        let hasSameName = false;
        do {
          index += 1;
          name = pageName + ` 副本${index}`;
          hasSameName = this.pageConfigList.some((page) => page.name === name);
        } while (hasSameName);
        return name;
      }
    }
  };
</script>

<style lang="scss" scoped>
  // 页面视图
  .page-view {
    width: 376px;

    .btn-addNewPage {
      width: 188px;
      height: 40px;
      font-size: 16px;

      .icon-new-page {
        width: 16px;
        height: 16px;
        vertical-align: text-top;
        @include bg('icons/icon-new-page.png');
      }
    }

    .btn-background {
      border-radius: 2px;
      width: 116px;
      height: 40px;
      font-size: 16px;
      background-color: #f8f8f8;

      .icon-fill-background {
        width: 16px;
        height: 16px;
        @include bg('icons/icon-fill-background.png');
      }
    }

    .page-wrapper {
      display: flex;
      flex-direction: column;
      // flex-direction: column-reverse;

      .page-index {
        border-radius: 50%;
        width: 32px;
        height: 32px;
        line-height: 32px;
        color: map-get($colors, 'light');
        background-color: #f8f8f8;
      }

      .active .page-index {
        color: map-get($colors, 'white');
        background-color: map-get($colors, 'theme');
        transition: all 0.3s;
      }

      .icon-turn-animation {
        width: 14px;
        height: 14px;
        @include bg('icons/icon-turn-animation.png');
      }

      .active .page-item {
        background-color: #f4f9ff;
        transition: all 0.3s;
      }

      .page-item {
        border-radius: 6px;
        width: 280px;
        background-color: map-get($bgColors, 'lightgrey');

        .pic-thumbnails {
          position: relative;
          width: 80px;
          height: 140px;
          background-color: #fff;
          box-shadow: 0 6px 20px 1px rgba(0, 5, 97, 0.04);

          .icon-create {
            width: 24px;
            height: 24px;
            @include bg('icons/icon-page.png');
          }
        }

        &.home {
          position: relative;

          .pic-thumbnails::before {
            position: absolute;
            top: 16px;
            left: 0;
            display: block;
            border-radius: 0 10px 10px 0;
            padding-left: 3px;
            width: 31px;
            font-size: 12px;
            line-height: 20px;
            color: #fff;
            background-color: rgba(0, 0, 0, 0.4);
            content: '\9996\9875';
          }
        }

        .icon {
          width: 14px;
          height: 14px;
        }

        .icon-edit {
          @include bg('icons/icon-edited.png');
        }

        .icon-editing {
          @include bg('icons/icon-editing.png');
        }

        .icon-copy {
          @include bg('icons/icon-copy.png');
        }

        .icon-delete {
          @include bg('icons/icon-del.png');
        }

        .aside-page-name-input {
          width: 144px;

          ::v-deep .el-input__inner {
            border-width: 0 0 1px;
            border-color: map-get($bdColors, 'theme') !important;
            border-radius: 0;
            padding: 0 0 4px;
            height: 20px;
            line-height: 1;
            color: map-get($colors, 'theme');
            background-color: transparent;
          }

          ::v-deep .el-input__suffix {
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
  }

  // 背景设置弹窗
  .pageBackground-dialog {
    ::v-deep {
      .el-dialog__body {
        padding: 0;
        min-height: 316px;

        > .tip {
          line-height: 28px;
          letter-spacing: 1px;
          background-color: #fff6e6;

          .svg-icon {
            color: #ffa900;
          }
        }

        .form-group {
          padding: 0 24px;
          background-color: map-get($bgColors, 'white');

          .el-form-item:not(:last-of-type) {
            margin-bottom: 12px;
          }
          // 渐变角度
          .linear-gradient-rotate {
            padding: 0;
            height: auto;
          }
          // 透明度配置
          .opacity-setting {
            padding: 0;
            width: 360px;
            height: auto;
          }
          // 预定义颜色面板
          .boxs-predefine-colors {
            padding-left: 0;
          }
        }
      }
    }
  }

  .force-fallback {
    visibility: hidden;
    cursor: move;
  }

  .sortable-ghost {
    cursor: move;
  }
</style>
